// 导入jsonwebtoken
const jwt = require("jsonwebtoken")
const {ValidationError} = require("./customError")
class JwtTool {
    static _jwtKey = "S9HReJWvXzhgQTyp"
    generate(res, maxAge = 3600 * 24 * 1000, info = {}){
        const jwtToken = jwt.sign(info, JwtTool._jwtKey, {
            expiresIn: maxAge
        })
        res.header("Authorization", jwtToken)
    }

    analysis(req){
        let token = req.headers.authorization
        // 没有token的情况下
        if (!token) return null
        // authorization: bearer token
        token = token.split(" ");
        token = token.length === 1 ? token[0] : token[1];

        try {
            return jwt.verify(token, JwtTool._jwtKey)
        } catch (e) {
            // jwt无效
            throw new ValidationError("身份已失效，请重新登录")
        }
    }
}

module.exports = new JwtTool()
